package com.library.service;

import com.library.constant.CommonConstant;
import com.library.entity.UserInfo;
import com.library.controller.RCException;
import com.library.mapper.UserInfoMapper;
import com.library.vo.UserInfoRes;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.function.Function;
import java.util.stream.Collectors;

@Service
public class UserInfoService {

    @Autowired
    private UserInfoMapper userInfoMapper;

    public void add(UserInfo oaDepartment) {
        UserInfo userInfo = new UserInfo();
        userInfo.setName(oaDepartment.getName());
        List<UserInfo> userInfos = this.userInfoMapper.selectByQuery(userInfo);
        if(!userInfos.isEmpty()){
            throw new RCException("员工名称重复了");
        }
        // 密码默认
        oaDepartment.setPassword("123123");
        this.userInfoMapper.insertSelective(oaDepartment);
    }

    public void delete(UserInfo oaDepartment) {
        this.userInfoMapper.deleteByPrimaryKey(oaDepartment.getId());
    }

    public UserInfo detail(UserInfo oaDepartment) {
        UserInfo userInfo = this.userInfoMapper.selectByPrimaryKey(oaDepartment.getId());
        return userInfo;
    }

    public void update(UserInfo userInfo) {
        int i = this.userInfoMapper.updateByPrimaryKey(userInfo);
    }

    public List<UserInfoRes> list(UserInfo userInfo) {
        List<UserInfo> userInfos = this.userInfoMapper.selectByQuery(userInfo);
        List<UserInfoRes> collect = userInfos.stream().map(new Function<UserInfo, UserInfoRes>() {
            @Override
            public UserInfoRes apply(UserInfo userInfo) {
                UserInfoRes target = new UserInfoRes();
                BeanUtils.copyProperties(userInfo, target);
                target.setRoleDesc(roleDesc(userInfo.getRole()));
                return target;
            }
        }).collect(Collectors.toList());
        return collect;
    }

    public static String roleDesc(String role) {
        switch (role) {
            case CommonConstant.ROLE_ADMIN:
                return CommonConstant.ROLE_ADMIN_desc;
            case CommonConstant.role_general_manager:
                return CommonConstant.role_general_manager_desc;
            case CommonConstant.role_manager:
                return CommonConstant.role_manager_desc;
            case CommonConstant.role_staff:
                return CommonConstant.role_staff_desc;
            default:
                return ""; // 或者可以返回 null，取决于你希望如何处理未知角色
        }
    }

}
